<template>
    <div>
        <Row>
            <Col span="24">
                <Card :padding="0">
                    <p slot="title">
                        账单编号：{{formValidate.seqno}}
                    </p>
                </Card>
            </Col>
        </Row>
        <div class="basic">基础信息</div>
        <Row>
            
            <Col span="8">
                <div class="label-box">
                    <span class="label">合同名称：</span>
                    <span>{{formValidate.contractName}}</span>
                </div>
            </Col>
            <Col span="8">
                <div class="label-box">
                    <span class="label">商户：</span>
                    <span>{{formValidate.clientName}}</span>
                </div>
            </Col>
            <Col span="8">
                <div class="label-box">
                    <span class="label">结算方式：</span>
                    <span>{{formValidate.contractPaymentTypeName}}</span>
                </div>
            </Col>
        </Row>
        <Row>
            
            <Col span="8">
                <div class="label-box">
                    <span class="label">云丁商务：</span>
                    <span>{{formValidate.principalName}}</span>
                </div>
            </Col>
            <Col span="8">
                <div class="label-box">
                    <span class="label">所属月份：</span>
                    <span>{{month}}</span>
                </div>
            </Col>
            <Col span="8">
                <div class="label-box">
                    <span class="label">账单类型：</span>
                    <span>{{formValidate.typeName}}</span>
                </div>
            </Col>
        </Row>
        <Row>
            
            <Col span="8">
                <div class="label-box">
                    <span class="label">创建时间：</span>
                    <span>{{createTime}}</span>
                </div>
            </Col>
        </Row>
        <Row>
            <Col span="8">
                <div class="label-box">
                    <span class="label">费用说明：</span>
                    <div class="table-box">
                        <Table stripe border :columns="columns" :data="renters" :loading="isLoading"></Table>
                    </div>
                </div>
            </Col>
        </Row>
        <div class="secondTabs">
            <Tabs 
            type="card" 
            closable 
            v-model="currentTab" 
            :animated="false" >
                <TabPane label="账单详情" style="background:#efeff1" :closable="false" :name="'0'">
                    <bill-tabs :id="this.$props.id"></bill-tabs>
                </TabPane>

                <!-- 回款记录 -->
                <TabPane :name="'1'" label="付款记录" style="background:#efeff1" :closable="false">
                    <!-- <div class="table-box"> -->
                    <div>
                        <Table stripe border :columns="backColumns" :data="backRenters" :loading="isLoading"></Table>
                    </div>
                    <Modal
                        title="新增回款记录"
                        v-model="show"
                        >
                        <Form :model="form" :rules="ruleValidate" ref="form" :label-width="120" class="padding-right-20">
                            <FormItem label="回款日期" prop="payDate">
                                <DatePicker 
                                    type="date" 
                                    v-model="form.payDate">
                                </DatePicker>
                            </FormItem>
                            <FormItem label="回款金额" prop="amount">
                                <i-input v-model="form.amount"></i-input>
                            </FormItem>
                            <FormItem label="附件" prop="file">
                                <Upload 
                                :action="action"
                                :data="aliOss"
                                :before-upload="beforeUpload"
                                :on-success="uploadSuccess"
                                >
                                    <Button icon="ios-cloud-upload-outline">上传附件</Button>
                                </Upload>
                                
                            </FormItem>
                            <FormItem label="备注" prop="remark">
                                <i-input type="textarea" v-model="form.remark"></i-input>
                            </FormItem>
                        </Form>

                        <Row slot="footer">
                            <Button type="text" @click="show=false">取消</Button>
                            <Button type="primary" :loading="loading" @click="handleSubmit('form')">确定</Button>
                        </Row>
                    </Modal>
                </TabPane>

            </Tabs>
        </div>
    </div>
</template>

<script>
import { http, api } from '@/libs/http'
import billTabs from './billTabs'
import validate from '@/libs/validate.js'
export default {
  components: {
    billTabs
  },
  props: {
    id: String,
    sendModelshow: Boolean
  },
  data () {
    return {
      show: false, // 回款记录model
      edit: {}, // 新增编辑类型
      formValidate: {},
      currentTab: '0',
      loading: false,
      aliOss: {}, // alioss
      action: '', // oss路径
      columns: [
        {
          title: '总金额（元）',
          key: 'totalCostAmount',
          align: 'center'
        },
        {
          title: '已收金额（元）',
          key: 'totalPaymentAmount',
          align: 'center'
        },
        {
          title: '未收金额（元）',
          key: 'totalUnPaymentAmount',
          align: 'center'
        },
        {
          title: '已开票金额',
          key: 'totalInvoiceAmount',
          align: 'center'
        }
      ],
      backColumns: [
        {
          title: '回款日期',
          key: 'payDate',
          align: 'center'
        },
        {
          title: '实际回款金额',
          key: 'amount',
          align: 'center'
        },
        {
          title: '备注',
          key: 'remark',
          align: 'center'
        },
        {
          title: '操作人',
          key: 'optName',
          align: 'center'
        }

      ],
      renters: [], // 费用列表
      backRenters: [], // 回款列表
      isLoading: false,
      form: {
        createBy: 0
      },
      ruleValidate: {
        payDate: [
          { type: 'date', required: true, message: '日期不能为空', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '预付款不能为空', trigger: 'blur' },
          { validator: validate.validDecmal2, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    if (this.$props.sendModelshow) {
      this.show = this.$props.sendModelshow
      this.currentTab = '1'
    }
    this.getBill(this.$props.id)
    this.handleInit(this.$props.id)
    this.fetchModels()
  },
  computed: {
    month () {
      return this.formValidate.month ? this.formValidate.month.substring(0, 7) : ''
    },
    createTime () {
      return this.formValidate.createTime ? this.formValidate.createTime.split(' ')[0] : ''
    }
  },
  methods: {
    async fetchModels () {
      let res = await http.fetch(this, api.enum, null, null)
      sessionStorage.setItem('device', JSON.stringify(res))
    }, // 设备
    async getBill (id) {
      this.formValidate = await http.fetch(this, api.bill_info, [id], null)
      this.renters = [{totalCostAmount: this.formValidate.totalCostAmount, totalPaymentAmount: this.formValidate.totalPaymentAmount, totalUnPaymentAmount: this.formValidate.totalUnPaymentAmount, totalInvoiceAmount: this.formValidate.totalInvoiceAmount}]
    }, // 账单详情
    handleSubmit (name) {
      this.loading = true
      this.form.billId = this.$props.id
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.edit.type === 'edit') {
            http.request(this, api.payment_update, null, this.form, (res, err) => {
              this.loading = false
              console.log(err, res)
              if (err || !res) return
              this.$Message.success('修改成功')
              this.form = {}
              this.show = false
              this.handleInit(this.$props.id)
            })
          } else {
            http.request(this, api.payment_create, null, this.form, (res, err) => {
              this.loading = false
              console.log(err, res)
              if (err || !res) return
              this.$Message.success('新增成功')
              this.form = {}
              this.show = false
              this.handleInit(this.$props.id)
            })
          }
        } else {
          this.loading = false
          this.$Message.error('请完整填写表单信息')
        }
      })
    }, // 新增回款记录
    async handleInit (id) {
      this.backRenters = (await http.fetch(this, api.payment_list, [id], null)).rows
    }, // 初始化数据

    handleEdit (row) {
      this.edit.type = 'edit'
      this.form = {
        paymentId: row.id,
        updateBy: row.createBy,
        payDate: row.payDate,
        amount: row.amount,
        remark: row.remark,
        billId: row.billId,
        file: row.file
      }
      this.show = true
    }, // 编辑
    handleDelete (row) {
      this.form = {
        paymentId: row.id,
        updateBy: row.createBy,
        billId: row.billId
      }
      this.$Modal.confirm({
        title: '删除回款记录?',
        content: '回款记录将会被删除',
        onOk: () => {
          http.request(this, api.payment_delete, null, this.form, (res, err) => {
            if (err || !res) return
            this.$Message.success('删除成功')
            this.form = {}
          })
        },
        onCancel: () => {
          this.$Message.info('已取消')
        }
      })
    }, // 回款记录删除
    uploadSuccess (response, file) {
      console.log(file)
    },
    beforeUpload (file) {
      return new Promise((resolve, reject) => {
        http.fetch(this, api.alioss, null, null).then(res => {
          console.log(res)
          let aliOss = {
            policy: res.policy,
            OSSAccessKeyId: res.accessKeyId,
            success_action_status: '200', // 让服务端返回200,不然，默认会返回204
            // callback: callbackbody,
            key: new Date().valueOf() + file.name,
            signature: res.signature
          }
          this.aliOss = aliOss
          this.action = res.host
          resolve()
        })
      })
    },
    capDevice (value) {
      let selectModels = JSON.parse(sessionStorage.getItem('device'))
      return selectModels.find((item) => {
        return value === item.id
      }).name
    } // 过滤设备
  }
}
</script>

<style lang="less" scoped>
    .label-box {
        .label {
            display: inline-block;
            width: 120px;
            padding-left: 30px;
            margin-bottom: 20px;
            margin-right: 10px;
        }
    }
    .table-box {
        border: 1px solid #dddee1;
        margin-left: 30px;
        width: 600px;
    }
    .basic {
        font-weight: 900;
        font-size: 14px;
        margin:20px 0;
        padding-left:10px;
        border-left:2px solid #05bac5;
    }
    .secondTabs {
        margin-top: 40px;
    }
</style>
<style lang="less">
    .secondTabs {
        .ivu-tabs.ivu-tabs-card>.ivu-tabs-bar .ivu-tabs-tab-active {
            background: #efeff1;
        }
        .ivu-tabs.ivu-tabs-card>.ivu-tabs-bar:before {
            border: none;
        }
        .table-box {
            margin-left: 0;
        }
    }
</style>
